package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "userCheckFilter", urlPatterns = "/shoppingCart/*")
@Slf4j
public class UserCheckFilter implements Filter {

    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("第三个拦截器");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String uri = request.getRequestURI();
        log.info("拦截到的uri {}",uri);
//        String[] urls = {
//                "/user/sendMsg",
//                "/user/login",
//                "/user/loginout",
//                "/backend/plugins/**",
//                "front/index.html",
//                "/front/page/login.html"
//        };
//        boolean check = check(urls, uri);
//        if (check){
//            log.info("不需要处理这个uri {}",uri);
//            filterChain.doFilter(servletRequest,servletResponse);
//            return;
//        }
        Long userId = (Long) request.getSession().getAttribute("user");
        if (userId != null){
            log.info("已登录");
            BaseContext.setId(userId);
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        log.info("未登录");
        R<Object> notlogin = R.error("NOTLOGIN");
        response.getWriter().write(JSON.toJSONString(notlogin));
        return;
    }

    //判断请求资源是否需要处理
    private boolean check(String[] urls,String uri) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, uri);
            if (match){
                return true;
            }
        }
        return false;
    }
}
